<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/7/23
 * Time: 15:16
 */

namespace app\common\lib;


use app\exception\IndexException;
use support\Cache;
use support\Redis;

class Oceanengine
{
    protected $domain = 'https://ad.oceanengine.com/';
    protected $domainApi = 'https://api.oceanengine.com/';

    protected static $instance;

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }


        return new self();
    }

    public function getTokenByAuthCode($authCode)
    {
        $url = $this->domain.'open_api/oauth2/access_token/';
        $header = [
            'Content-Type: application/json;',
            'X-Debug-Mode: 1'
        ];
        $config = config('param.oceanengine');
        $param = [
            'app_id'=>$config['appid'],
            'secret'=>$config['secret'],
            'grant_type'=>'auth_code',
            'auth_code'=>$authCode,
        ];
        $result = Common::curlApi($url,$param,true,$header);

        if(isset($result['data']) && !empty($result['data']['access_token'])){

            $result['data']['expires_time'] = time()+$result['data']['expires_in']-7200;

            Redis::connection('common')->set('oceanengine_token_data', serialize($result['data']));

            return $result['data'];
        }

        return false;
    }

    public function getRefreshToken()
    {
        $data =  Redis::connection('common')->get('oceanengine_token_data');
        $data = unserialize($data);
//        var_dump($data);
//        $data['expires_time'] = 0;
//        $data['refresh_token'] = 'b9774568100a121ed793ea05ec88195c4d29951b';
        if($data && $data['expires_time']>time()){
            return $data['access_token'];
        }else{
            $url = $this->domainApi.'open_api/oauth2/refresh_token/';
            $header = [
                'Content-Type: application/json',
                'X-Debug-Mode: 1'
            ];
            $config = config('param.oceanengine');
            $param = [
                'app_id'=>$config['appid'],
                'secret'=>$config['secret'],
                'grant_type'=>'refresh_token',
                'refresh_token'=>$data['refresh_token'],
            ];
            $result = Common::curlApi($url,$param,true,$header);
            //var_dump($param,$result);
            if(isset($result['data']) && !empty($result['data']['access_token'])){

                $result['data']['expires_time'] = time()+$result['data']['expires_in']-7200;

                Redis::connection('common')->set('oceanengine_token_data', serialize($result['data']));

                return $result['data']['access_token'];
            }
        }
    }

    public function getNotAcceptedTaskList($page=1)
    {
        $token = $this->getRefreshToken();
        $pageSize = 10;
        $header = [
            'Access-Token:'.$token,
        ];

        $param = [
            'star_id'=>1802729155885289,
            'min_create_time_stamp'=>strtotime(date('Y-m-d',strtotime('-3 day'))),
            'page'=>$page,
            'page_size'=>$pageSize,
        ];

        $url = $this->domainApi.'open_api/2/star/mcn/get_unparticipated_task/';
        $data = Common::curlApi($url,$param,false,$header);
        //var_dump($token,$data);
        if(empty($data['code'])){
            return $data['data'];
        }
        throw new IndexException(($data['code']??4020),($data['message']??'获取未参与任务失败'));
    }

    public function getAcceptedTaskList($page=1)
    {
        $token = $this->getRefreshToken();
        $pageSize = 10;
        $header = [
            'Access-Token:'.$token,
        ];

        $param = [
            'star_id'=>1802729155885289,
            'page'=>$page,
            'page_size'=>$pageSize,
        ];

        $url = $this->domainApi.'open_api/2/star/mcn/get_contracted_challenge_list/';
        $data = Common::curlApi($url,$param,false,$header);
        //var_dump($param,$data);
        if(empty($data['code'])){
            return $data['data'];
        }
        throw new IndexException(($data['code']??4020),($data['message']??'获取参与任务失败'));
    }

    public function acceptedTask($task)
    {
        $token = $this->getRefreshToken();
        $header = [
            'Content-Type: application/json',
            'Access-Token:'.$token,
        ];

        $param = [
            'star_id'=>1802729155885289,
            'demand_id'=>$task['demand_id'],
            'mcn_profit_rate'=>700,     //达人分佣统一是70% 千分之一
        ];

        $url = $this->domainApi.'open_api/2/star/mcn/contract_challenge/';
        $data = Common::curlApi($url,$param,true,$header);
        //var_dump($data,$param);
        if(empty($data['code'])){
            return $data['data'];
        }
        throw new IndexException(($data['code']??4020),'任务Id '.$task['demand_id'].",".($data['message']??'接受任务失败'));
    }

    /**
     * 获取任务链接
     * @param $taskId
     * @param $userSn
     * @return mixed
     * @throws \Exception
     */
    public function getTaskLink($taskId,$userSn)
    {
        $token = $this->getRefreshToken();
        $header = [
            'Access-Token:'.$token,
        ];

        $param = [
            'star_id'=>1802729155885289,
            'demand_id'=>(int)$taskId,
            'channel_id'=>(string)$userSn,     //渠道id，传用户编号过去，没有对应渠道分佣，应该会按兜底分佣比例
        ];

        $url = $this->domainApi.'open_api/2/star/mcn/get_contracted_challenge_url/';
        $data = Common::curlApi($url,$param,false,$header);
        //var_dump($data,$param);
        if(empty($data['code'])){
            return $data['data'];
        }
        throw new IndexException(($data['code']??4020),($data['message']??'获取任务链接失败'));
    }

    /**
     * 获取投后数据信息
     * @param $taskId
     * @param $page
     * @return mixed
     * @throws \Exception
     */
    public function getTalentVideoIncomeData($taskId,$page=1)
    {
        $token = $this->getRefreshToken();
        $header = [
            'Access-Token:'.$token,
        ];

        $param = [
            'star_id'=>1802729155885289,
            'demand_id'=>(int)$taskId,
            'page'=>(int)$page,
            'page_size'=>(int)30,
        ];

        $url = $this->domainApi.'open_api/2/star/mcn/get_contract_challenge_author_item_list_v2/';
        $data = Common::curlApi($url,$param,false,$header);
        //var_dump($data,$param);
        if(empty($data['code'])){
            return $data['data'];
        }
        throw new IndexException(($data['code']??4020),($data['message']??'获取投后数据信息失败'));
    }

    public function getOceanengineAdAttribution($platform,$device)
    {
        $param = [];
        if(strtolower($platform)=='ios'){
            $param['idfv'] = $device;
            $param['package_name'] = 'ai.tuiwen.xy';
        }elseif(strtolower($platform)=='android'){
            $param['android_id'] = $device;
            $param['package_name'] = 'ai.tuiwen.xy';
        }
        if(empty($param)){
            return [];
        }
        $param['platform'] = strtolower($platform);
        $result = Guzzle::post('https://analytics.oceanengine.com/','sdk/app/attribution',$param);

        return $result;
    }

    public function submitConversion($event,$callbackParam,$device=[],$properties=[])
    {
        /**
         {
                "event_type": "active",  //active  active_register  active_pay
                "event_weight": 0.21312,
                "context": {
                     "ad": {
                        "callback": "demo_callback",
                        "match_type": 3
                     },
                     "device": {
                        "platform": "ios",
                        "idfa": "FCD369C3-F622-44B8-AFDE-12065659F34B"
                     }
                },
                "properties": {
                    "pay_amount": 1231.211
                },
                "timestamp": 1604888786102
         }
         */

        $param = [
            'event_type'=>$event,
            'context'=>[
                'ad'=>[
                    'callback'=>$callbackParam,
                    'match_type'=>0,
                ]
            ],
        ];
        if(!empty($device)){
            $param['context']['device'] = $device;
        }
        if(!empty($properties)){
            $param['properties'] = $properties;
        }
        $param['timestamp'] = round(microtime(true)*1000);

        $heads = [
            'Content-Type'=>'application/json',
        ];
        $res = Guzzle::post('https://analytics.oceanengine.com/','api/v2/conversion',$param,$heads,'json');

        return $res;
    }
}